<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <span style="font-size: 18px;line-height: 24px;color: #303133; margin-left: -20px;">标准明细</span>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleSelect"
          style="margin-left: 10px;"
          v-hasPermi="['hr:wageStandard:add']"
          v-if="optType !== 'view'"
        >选择产品</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-card style="border-radius: 10px">
      <el-table
          v-loading="loading"
          :data="wageStandardLineList"
          border
          @cell-mouse-enter="handleCellEnter()"
          @cell-mouse-leave="handleCellLeave()">
        <el-table-column label="产品物料编码" align="center" prop="itemCode" />
        <el-table-column label="产品物料名称" align="center" prop="itemName" />
        <el-table-column label="规格型号" align="center" prop="specification" />
        <el-table-column label="计价方式" align="center" prop="pricingManner" >
          <template slot-scope="scope">
            <el-select
                v-model="scope.row.pricingManner"
                placeholder="请选择计价方式"
                @focus="(event) => onTaxRateFocus(scope.row)"
                @change="(value) => handleSelectChange(value, scope.row, scope.row.pricingManner)"
                :disabled="optType === 'view'"
            >
              <el-option value="time" label="计时"> </el-option>
              <el-option value="piece" label="计件"> </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="unitPrice">
          <div class="item" slot-scope="scope">
            <el-input
                class="item_input"
                v-model="scope.row.unitPrice"
                size="mini"
                style="width: 100%;"
                :title="scope.row.unitPrice"
                @blur="handleBlur(scope.row)"
                v-if="optType !== 'view'"
            />
            <el-input
                class="item_input"
                v-model="scope.row.unitPrice"
                size="mini"
                style="width: 100%;"
                :title="scope.row.unitPrice"
                readonly
                v-if="optType === 'view'"
            />
          </div>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType !== 'view'">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['hr:wageStandard:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>

  </div>
</template>

<script>
import {
  listWageStandard,
  getWageStandard,
  delWageStandard,
  addWageStandard,
  updateWageStandard
} from "@/api/mes/hr/wageStandard";
import ItemSelect from "@/components/itemSelect/single.vue"

export default {
  name: "WageStandardLine",
  components: { ItemSelect },
  props: {
    processId: null,
    workstationId: null,
    machineryId: null,
    optType: null
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计价工资标准表格数据
      wageStandardLineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processId: this.processId,
        processCode: null,
        processName: null,
        workstationId: this.workstationId,
        workstationCode: null,
        workstationName: null,
        machineryId: this.machineryId,
        machineryCode: null,
        machineryName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        pricingManner: null,
        unitPrice: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 可修改单元格属性
      editProp: ['unitPrice'],
      // 原计价方式
      originalPricingManner: null,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    processId: function (newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.queryParams.processId = newVal;
        this.getList();
      }
    },
    workstationId: function (newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.queryParams.workstationId = newVal;
        this.getList();
      }
    },
    machineryId: function (newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.queryParams.machineryId = newVal;
        this.getList();
      }
    },
  },
  methods: {
    /** 查询计价工资标准明细列表 */
    getList() {
      this.loading = true;
      listWageStandard(this.queryParams).then(response => {
        this.wageStandardLineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        processId: this.processId,
        processCode: null,
        processName: null,
        workstationId: this.workstationId,
        workstationCode: null,
        workstationName: null,
        machineryId: this.machineryId,
        machineryCode: null,
        machineryName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        pricingManner: null,
        unitPrice: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除计价工资标准编号为"' + ids + '"的数据项？').then(function() {
        return delWageStandard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hr/wageStandard/export', {
        ...this.queryParams
      }, `wageStandard_${new Date().getTime()}.xlsx`)
    },
    // 打开产品选择框
    handleSelect() {
      this.$refs.itemSelect.showFlag = true;
    },
    // 选择产品回调
    onItemSelected(obj) {
      if(obj !== undefined && obj !== null){
        this.reset();
        this.form.processId = this.processId;
        this.form.workstationId = this.workstationId;
        this.form.machineryId = this.machineryId;
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        addWageStandard(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
        });
      }
    },
    // 列表单元格鼠标进入事件
    handleCellEnter (row, column, cell, event) {
      if (column) {
        const property = column.property
        if (this.editProp.includes(property)) {
          cell.querySelector('.item_input').style.display = 'block'
        }
      }
    },
    // 列表单元格鼠标离开事件
    handleCellLeave (row, column, cell, event) {
      if (column) {
        const property = column.property
        if (this.editProp.includes(property)) {
          cell.querySelector('.item_input').style.display = 'none'
        }
      }
    },
    // 列表单元格输入框失去焦点事件
    handleBlur(row) {
      const unitPrice = row.unitPrice;
      const pattern = /^\d+(\.\d+)?$/;
      if (!pattern.test(unitPrice)) {
        this.$modal.msgError("单价必须为数字，且不能包含特殊字符或文字");
        row.unitPrice = unitPrice; // 恢复原值
        return;
      }

      const float = parseFloat(row.unitPrice);
      if (float <= 0) {
        this.$modal.msgError("单价必须大于 0");
        row.unitPrice = unitPrice; // 恢复原值
        return;
      }

      updateWageStandard(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    // 获取原数据
    onTaxRateFocus(row) {
      this.originalPricingManner = row.pricingManner;
    },
    // 计价方式变更
    handleSelectChange(value, row) {
      const oldValue = this.originalPricingManner;
      // 如果值未发生变化，不进行请求
      if (value === oldValue) return;
      updateWageStandard(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      }).catch(error => {
        this.$modal.msgError("修改失败，请重试");
        console.error("修改失败", error);
      });
    },


  }
};
</script>
